package com.pubinfo.passbook.data.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.entity.TPassbookPersionInfo;
import com.pubinfo.passbook.common.entity.TSubsidiaryInfo;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.common.mapper.TSubsidiaryPrivateKeyMapper;
import com.pubinfo.passbook.common.model.bo.SubsidiaryInfo;
import com.pubinfo.passbook.common.model.dto.financial.InvoiceResult;
import com.pubinfo.passbook.common.model.dto.financial.Result;
import com.pubinfo.passbook.common.service.cache.JedisManage;
import com.pubinfo.passbook.common.service.master.TPassbookPersionInfoService;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.common.service.master.TSubsidiaryInfoService;
import com.pubinfo.passbook.common.service.request.financial.RequestFinancialServer;
import com.pubinfo.passbook.data.quartz.service.InvoiceServer;
import com.pubinfo.passbook.data.quartz.service.MedicineOnJobOrRetireAutoReimbursement;
import com.pubinfo.passbook.data.service.TFileInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class InvoiceServerImpl implements InvoiceServer {
  @Autowired
  TPassbookService passbookService;
  @Autowired
  private TSubsidiaryPrivateKeyMapper keyMapper;
  @Autowired
  JedisManage redisService;
  @Autowired
  TPassbookPersionInfoService persionInfoService;
  @Autowired
  RequestFinancialServer financialServer;
  @Autowired
  TFileInfoService tFileInfoService;
  @Autowired
  MedicineOnJobOrRetireAutoReimbursement retireAutoReimbursement;
  @Autowired
  TSubsidiaryInfoService infoService;
  @Autowired
  TSourcePassbookMapper passbookMapper;
  
  @Override
  public void receiveInvoiceList() {
    QueryWrapper<TPassbookPersionInfo> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("is_succeed", "0");
    List<TPassbookPersionInfo> infoList = persionInfoService.list(queryWrapper);
    if (CollectionUtils.isNotEmpty(infoList)) {
      List<TPassbook> passbookAllList = insertInvoice(infoList);
      //先不发起报销，另外一个任务中发起报账
      // retireAutoReimbursement.autoJobReimbursement(passbookAllList);
      passbookMapper.updateInvoiceStatus(); //设置冲红票据状态
    }
  }
  
  @Transactional
  public List<TPassbook> insertInvoice(List<TPassbookPersionInfo> infoList) {
    List<TPassbook> passbookAllList = new ArrayList<>();//保存全部的票据
    infoList.stream().forEach(info -> {
      List<SubsidiaryInfo> subsidiaryInfos = keyMapper.listFinAllSubsidiaryInfo(info.getEnterId());
      InvoiceResult<Result> invoiceResult = financialServer.detailList(info.toList(), subsidiaryInfos.get(0));
      if (invoiceResult.getResult() != null && invoiceResult.getSuccess()) {
        List<Result> resultList = invoiceResult.getResult();
        List<TPassbook> sourceTPassbookList = new ArrayList<>();
        List<TPassbook> finalSourceTPassbookList = sourceTPassbookList;
        resultList.stream().forEach(result -> {
          TPassbook passbook = new TPassbook();
          passbook.setNsrsbh(info.getEnterId());
          passbook.setAllResult(result);
//          passbook.setPayerPartyCode(info.getUsercode());
//          passbook.setPayerPartyName(info.getUsername());
          //  passbook.setPayerPartyType("1");
          //如果交款人名称不为空，则通过查询数据库获取交款人代码
          if (StringUtils.isNotBlank(passbook.getPayerPartyName())) {
            QueryWrapper<TSubsidiaryInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", passbook.getPayerPartyName());
            List<TSubsidiaryInfo> subsidiaryInfoList = infoService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(subsidiaryInfoList)) {
              passbook.setPayerPartyCode(subsidiaryInfoList.get(0).getNsrsbh());
            }
          }
          if (StringUtils.isBlank(passbook.getPayerPartyCode()) || passbook.getPayerPartyCode().length() < 17) {
            //设置默认
            passbook.setPayerPartyCode(info.getUsercode());
          }
          passbook.setPersionId(info.getId());
          finalSourceTPassbookList.add(passbook);
        });
        QueryWrapper<TPassbook> queryWrapper = new QueryWrapper<>();
        List<String> sourceList = sourceTPassbookList.stream().map(TPassbook::getEInvoiceId).collect(Collectors.toList());
        queryWrapper.in("e_invoice_id", sourceList);
        List<TPassbook> passbooks = passbookService.list(queryWrapper);
        //取源数据与查询数据的差集
        List<String> dbList = passbooks.stream().map(TPassbook::getEInvoiceId).collect(Collectors.toList());
        sourceList.removeAll(dbList);
        List<TPassbook> insertList = sourceTPassbookList.stream().filter(e -> sourceList.contains(e.getEInvoiceId())).collect(Collectors.toList());
        //为空代表已经全部保存成功
        if (CollectionUtils.isEmpty(insertList) || passbookService.saveBatch(insertList)) {
          info.setIsSucceed(1);
          persionInfoService.updateById(info);
        }
        passbookAllList.addAll(insertList);
      }
    });
    return passbookAllList;
  }
  
}
